package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.HealthRecordsCategoryAdapter;
import com.xn.app.muying.bean.HealthRecordsCategoryBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 健康档案列表详情
 * Created by Administrator on 2017/4/17.
 */
public class HealthRecordsCategoryActivity extends BaseActivity implements View.OnClickListener {
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //分类显示
    private GridView gridview;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    private HealthRecordsCategoryAdapter adapter;
    //加载框
    AlertDialog dialog;
    //数据库
    private DBManager db = null;
    private TextView nodata;
    private String testSpecies;
    private ArrayList<HealthRecordsCategoryBean> list = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_healthrecordscategory);
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        if (NetworkUtil.isNetworkAvailable(this)) {
            initView();
            //数据下载
            HealthRecordsCategoryLoading();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    //数据下载
    private void HealthRecordsCategoryLoading() {
        dialog = new MyAlertDialog().ShowDialog(HealthRecordsCategoryActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.HealthRecordsCategory(getIntent().getStringExtra("registerID"))).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();

                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    onJsonHealthRecordsCategoryData(msg.obj.toString());
                    break;

                case 1:
                    ToastUtil.showToast(HealthRecordsCategoryActivity.this, "获取数据失败");
                    break;
            }
        }
    };

    //处理数据，填充数据
    private void onJsonHealthRecordsCategoryData(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String inpid = object.optString("inpid");
                testSpecies = object.optString("testSpecies");
                String testSpeciesImageURL = object.optString("testSpeciesImageURL");
                String pk = object.optString("pk");
                HealthRecordsCategoryBean healthRecordsCategoryBean = new HealthRecordsCategoryBean();
                healthRecordsCategoryBean.setInpid(inpid);
                healthRecordsCategoryBean.setTestSpecies(testSpecies);
                healthRecordsCategoryBean.setTestSpeciesImageURL(testSpeciesImageURL);
                healthRecordsCategoryBean.setPk(pk);
                list.add(healthRecordsCategoryBean);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (testSpecies != null) {
                        gridview.setVisibility(View.VISIBLE);
                        nodata.setVisibility(View.GONE);
                    } else {
                        gridview.setVisibility(View.GONE);
                        nodata.setVisibility(View.VISIBLE);
                    }
                }
            });
            adapter.getData(list);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        gridview = (GridView) findViewById(R.id.activity_healthrexordscategory_gridview);
        nodata = (TextView) findViewById(R.id.nodata_tv);
        title_name.setText("健康档案");
        img_back.setOnClickListener(this);
        adapter = new HealthRecordsCategoryAdapter(HealthRecordsCategoryActivity.this, imageLoader, options);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list != null) {
                    Intent intent = new Intent();
                    intent.putExtra("pk", list.get(position).getPk());
                    intent.setClass(HealthRecordsCategoryActivity.this, HealthRecordsDetailsActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }
}
